Given an integer k
, return the minimum number of Fibonacci numbers whose sum is equal tok
. The same Fibonacci number can be used multiple times.
The Fibonacci numbers are defined as:
F1 = 1
F2 = 1
Fn = Fn-1 + Fn-2
forn > 2
.
It is guaranteed that for the given constraints we can always find such Fibonacci numbers that sum up to k
.
Input: k = 7 Output: 2 Explanation: The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ... For k = 7 we can use 2 + 5 = 7.
Input: k = 10 Output: 2 Explanation: For k = 10 we can use 2 + 8 = 10.
Input: k = 19 Output: 3 Explanation: For k = 19 we can use 1 + 5 + 13 = 19.
1 <= k <= 10^9
# @param {Integer} k# @return {Integer}deffind_min_fibonacci_numbers(k)nums=[1,1]ret=0nums.push(nums[-2] + nums[-1])whilenums[-1] < kwhilek > 0nums.popwhilenums[-1] > kk -= nums[-1]ret += 1endretend
implSolution{pubfnfind_min_fibonacci_numbers(mutk:i32) -> i32{letmut nums = vec![1,1];letmut i = 1;letmut ret = 0;while nums[i] < k { nums.push(nums[i - 1] + nums[i]); i += 1;}while k > 0{while nums[i] > k { i -= 1;} k -= nums[i]; ret += 1;} ret }}